﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using QuickApp.Core;
using EfSearchModel.Model;
using QuickApp.MVCControl;
using Resto.CostControl.Core;
using QuickApp.MVCControl.Form;
using Resto.CostControl.Core.Models;

namespace Resto.CostControl.Web.Controllers
{
    public class MaterialProcessStorageController : Controller
    {
        private readonly IRepository<MaterialProcess> _Repo;
        private readonly IRepository<MaterialProcessItem> _RepoItem;
        private readonly IRepository<Storage> _RepoSt;
        private readonly IRepository<Material> _RepoMaterial;
        private readonly IRepository<StockRecord> _RepoStockRecord;
        private readonly IUnitOfWork _UnitOfWork;

        public MaterialProcessStorageController(IRepository<MaterialProcess> repo, IRepository<MaterialProcessItem> repoItem, IRepository<Storage> RepoSt, IRepository<Material> RepoMaterial, IRepository<StockRecord> RepoStockRecord, UnitOfWork unitOfWork)
        {
            _Repo = repo;
            _RepoItem = repoItem;
            _RepoSt = RepoSt;
            _RepoMaterial = RepoMaterial;
            _RepoStockRecord = RepoStockRecord;
            _UnitOfWork = unitOfWork;
        }

        public ActionResult Index()
        {
            return View();
        }

        [AcceptVerbs(HttpVerbs.Post)]
        public JsonResult Index(DWZPageInfo pageInfo, DWZQueryModel where)
        {
            where.AddItem("OrderState", "Picking");
            var list = _Repo.GetPageable(pageInfo.ToPageInfo(), where);
            var fdata = pageInfo.ToFlexiGridData<MaterialProcess>(list.Page.ToList(), list.Total);
            return Json(fdata);
        }

        public ActionResult Edit(string Id)
        {
            MaterialProcess data = null;
            if (!string.IsNullOrWhiteSpace(Id))
            {
                data = _Repo.Find(Id);
            }
            else
            {
                throw new ArgumentException("参数错误！");
            }
            return View(data);
        }

        [HttpPost]
        public JsonResult Save(MaterialProcess data, IList<MaterialProcessItem> MaterialList)
        {
            JsonReturnMessages msg = new JsonReturnMessages();
            if (ModelState.IsValid)
            {
                try
                {
                    var oldData = _Repo.Find(data.Id);
                    oldData.OrderState = "Storage";

                    foreach (var m in MaterialList)
                    {
                        var childdata = _RepoItem.Find(m.Id);
                        childdata.ActualStorageCount = m.ActualStorageCount;
                        childdata.State = "Storage";

                        //当入库单的状态为“入库”时 需要向库存表中写入信息
                        Storage Sordate = new Storage();
                        if (_RepoSt.Find(s => s.MaterialId == m.MaterialId) == null)
                        {
                            var Material = _RepoMaterial.Find(m.MaterialId);
                            Sordate.Id = Guid.NewGuid().ToString();
                            Sordate.ActualSorage = m.ActualStorageCount;
                            Sordate.MaterialId = m.MaterialId;
                            Sordate.Code = m.Code;
                            Sordate.Name = m.Name;
                            Sordate.Category = m.Category;
                            Sordate.Specification = Material.Specification;
                            Sordate.Unit = Material.Unit;
                            Sordate.Type = "SemiMaterial";
                            Sordate.CurrentPrice = Material.CurrentPrice;
                            _RepoSt.Insert(Sordate);
                        }
                        else
                        {
                            Sordate = _RepoSt.Find(s => s.MaterialId == m.MaterialId);
                            Sordate.ActualSorage += m.ActualStorageCount;
                        }

                        //保存库存记录
                        StockRecord StockRecorddate = new StockRecord()
                        {
                            Id = Guid.NewGuid().ToString(),
                            MaterialId = m.MaterialId,
                            Type = "加工领料",
                            Count = m.ActualStorageCount,
                        };
                        _RepoStockRecord.Insert(StockRecorddate);
                    }

                    _UnitOfWork.Commit();
                    msg.IsSuccess = true;
                    msg.Msg = "操作成功";
                }
                catch (Exception ex)
                {
                    msg.IsSuccess = false;
                    msg.Msg = "操作失败：" + ex.Message;
                }
            }

            return Json(msg);
        }

        [AcceptVerbs(HttpVerbs.Post)]
        public JsonResult Delete(string id)
        {
            JsonReturnMessages msg = new JsonReturnMessages();
            if (!string.IsNullOrEmpty(id))
            {
                try
                {
                    _Repo.Delete(id);
                    _UnitOfWork.Commit();
                    msg.IsSuccess = true;
                    msg.Msg = "操作成功";
                }
                catch
                {
                    msg.IsSuccess = false;
                    msg.Msg = "操作失败,请稍后重试！";
                }
            }
            else
            {
                msg.IsSuccess = false;
                msg.Msg = "参数错误";
            }
            return Json(msg);
        }
        [AcceptVerbs(HttpVerbs.Post)]
        public JsonResult MaterialList(DWZPageInfo pageInfo, DWZQueryModel where)
        {
            var list = _RepoItem.GetPageable(pageInfo.ToPageInfo(), where);
            var fdata = pageInfo.ToFlexiGridData<MaterialProcessItem>(list.Page.ToList(), list.Total);
            return Json(fdata);
        }

        public ActionResult EditList()
        {
            return View();
        }

        [AcceptVerbs(HttpVerbs.Post)]
        public JsonResult EditList(string parentId, DWZPageInfo pageInfo, DWZQueryModel where)
        {
            where.AddItem("OrderId", parentId == "" ? null : parentId);
            var list = _RepoItem.GetPageable(pageInfo.ToPageInfo(), where);
            var fdata = pageInfo.ToFlexiGridData<MaterialProcessItem>(list.Page.ToList(), list.Total);
            return Json(fdata);
        }

        [AcceptVerbs(HttpVerbs.Post)]
        public JsonResult DeleteItem(string Id)
        {
            JsonReturnMessages msg = new JsonReturnMessages();
            if (!string.IsNullOrEmpty(Id))
            {
                try
                {
                    _RepoItem.Delete(Id);
                    _UnitOfWork.Commit();

                }
                catch
                {
                    msg.IsSuccess = false;
                    msg.Msg = "操作失败,请稍后重试！";
                }
            }
            else
            {
                msg.IsSuccess = false;
                msg.Msg = "参数错误";
            }
            return Json(msg);
        }

        [HttpPost]
        public JsonResult Storage(string Id)
        {
            var data = _Repo.Find(Id);
            var MaterialList = _RepoItem.FindAll(m => m.OrderId == Id).ToList();

            return Save(data, MaterialList);
        }
    }
}